package com.cadre.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cadre.common.core.domain.model.LoginUser;
import com.cadre.common.utils.R;
import com.cadre.common.utils.SecurityUtils;
import com.cadre.common.utils.common.GenerateUUID;
import com.cadre.common.utils.oldutil.DateUtil;
import com.cadre.common.utils.oldutil.PageUtils;
import com.cadre.common.utils.oldutil.Query;
import com.cadre.common.utils.oldutil.ValidatorUtils;
import com.cadre.system.domain.officer.*;
import com.cadre.system.mapper.A01Mapper;
import com.cadre.system.mapper.B01Mapper;
import com.cadre.system.mapper.B50Mapper;
import com.cadre.system.mapper.ChartMapper;
import com.cadre.system.service.B04Service;
import com.cadre.system.service.B41Service;
import com.cadre.system.service.ISysRoleService;
import com.cadre.system.service.UnitInfoService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service("UnitInfoService")
public class UnitInfoServiceImpl extends ServiceImpl<B01Mapper, B01> implements UnitInfoService {


    @Autowired
    B50Mapper b50m;
    @Autowired
    B01Mapper b01m;
    @Autowired
    ChartMapper chartm;
    @Autowired
    private A01Mapper a01Mapper;
    @Autowired
    private B04Service b04Service;
    @Resource
    ISysRoleService sysRoleDataService;
    @Autowired
    private B41Service b41Service;
    @Autowired
    private B01Mapper b01Mapper;
    private List<B01> allList = new ArrayList();
    private List<B01> updateList = new ArrayList();
    @Override
    public List<B01> selectList(Wrapper<B01> wrapper) {
        return b01Mapper.selectList(wrapper);
    }
    @Override
    public PageUtils getChildListForPage(Map<String, Object> map) {
        String currentPage = map.get("pageNum").toString();
        String pageSize = map.get("pageSize").toString();
        map.put("page", currentPage);
        map.put("limit", pageSize);
        Page<B01> page = new Query(map).getPage();
        List<B01> list = this.b01m.selectList(page, map);
        return new PageUtils(page.setRecords(list));
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<Cadre_dictionary> getB0120(String key) {
        return this.baseMapper.getB0120(key);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<Tree> getB0122() {
        return this.baseMapper.getB0122();
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<Tree> getB0118() {
        return this.baseMapper.getB0118();
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public B01 getUnitInfoById(String flowid) {
        return this.baseMapper.selectByPrimaryKey(flowid);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public R LeaderNumber(String unitId) {
        if (!StringUtils.isNotBlank(unitId)) {
            return R.error("单位id未能获取！");
        }
        return R.ok().put("data", (Object) this.baseMapper.selectLeaderCount(Arrays.asList(unitId.split(","))));
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public R WorkNum(String unitId) {
        if (!StringUtils.isNotBlank(unitId)) {
            return R.error("单位id未能获取！");
        }
        return R.ok().put("data", (Object) this.baseMapper.selectStaffingLevelCount(Arrays.asList(unitId.split(","))));
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public void addUnit(B01 b) {;
        if (1 == this.baseMapper.insert(b)) {
        }
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public R LeaderNumbers(String unitIds) {
        LeaderCount leaderCount;
        if (!StringUtils.isNotBlank(unitIds)) {
            return R.error("单位id未能获取！");
        }
        String[] split = unitIds.split(",");
        List<String> list = Arrays.asList(split);
        List<LeaderCount> countList = this.baseMapper.selectLeaderCount(list);
        for (String unitId : split) {
            try {
                String zzRenyuan = getzzRenyuan(unitId);
                String fzRenyuan = getfzRenyuan(unitId);
                for (int j = 0; j < countList.size(); j++) {
                    if (countList.get(j).getFlowid().equals(unitId)) {
                        countList.get(j).setB0145a(zzRenyuan);
                        countList.get(j).setB0146a(fzRenyuan);
                    }
                }
            } catch (Exception e) {
            }
        }
        if (!CollectionUtils.isEmpty(countList) && (leaderCount = this.baseMapper.selectSum(list)) != null) {
            leaderCount.setB0101("总计");
            countList.add(leaderCount);
        }
        return R.ok().put("data", (Object) countList);
    }

    private String getfzRenyuan(String unitId) {
        StringBuffer s_fz = new StringBuffer();
        String result = "";
        Map<String, Object> map = new HashMap<>();
        map.put("unitId", unitId);
        map.put("zhiwu", "副职");
        List<TeamMember> teamMembers = this.baseMapper.getteamLeaders(map);
        for (int i = 0; i < teamMembers.size(); i++) {
            try {
                s_fz.append("【" + teamMembers.get(i).getXm() + "," + teamMembers.get(i).getXb() + "," + DateUtil.dateToString(teamMembers.get(i).getCsrq(), DateUtil.MONTG_DATE_FORMAT) + "】，");
            } catch (Exception e) {
            }
        }
        try {
            result = s_fz.toString().substring(0, s_fz.toString().length() - 1);
        } catch (Exception e2) {
        }
        return result;
    }

    private String getzzRenyuan(String unitId) {
        StringBuffer s_zz = new StringBuffer();
        String result = "";
        Map<String, Object> map = new HashMap<>();
        map.put("unitId", unitId);
        map.put("zhiwu", "正职");
        List<TeamMember> teamMembers = this.baseMapper.getteamLeaders(map);
        for (int i = 0; i < teamMembers.size(); i++) {
            try {
                s_zz.append("【" + teamMembers.get(i).getXm() + "," + teamMembers.get(i).getXb() + "," + DateUtil.dateToString(teamMembers.get(i).getCsrq(), DateUtil.MONTG_DATE_FORMAT) + "】，");
            } catch (Exception e) {
            }
        }
        try {
            result = s_zz.toString().substring(0, s_zz.toString().length() - 1);
        } catch (Exception e2) {
        }
        return result;
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public R WorkNums(String unitIds) {
        StaffingLevelCount count;
        if (!StringUtils.isNotBlank(unitIds)) {
            return R.error("单位id未能获取！");
        }
        List<String> list = Arrays.asList(unitIds.split(","));
        List<StaffingLevelCount> countList = this.baseMapper.selectStaffingLevelCount(list);
        if (!CollectionUtils.isEmpty(countList) && (count = this.baseMapper.selectStaffingLevelSum(list)) != null) {
            count.setB0101("总计");
            countList.add(count);
        }
        return R.ok().put("data", (Object) countList);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<Chart> getSexProport(String unitId) {
        return this.chartm.getSexProport(unitId);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<Chart> getAgeProport(String unitId) {
        return this.chartm.getAgeProport(unitId);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<Chart> getEducationProport(String unitId) {
        return this.chartm.getEducationProport(unitId);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public void exportExcel(String unitId, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isNotBlank(unitId)) {
            List<StaffingLevelCount> countList = this.baseMapper.selectStaffingLevelCount(Arrays.asList(unitId.split(",")));
            if (countList.size() > 0) {
                workExcel(request, response, countList);
            }
        }
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public void exportExcel2(String unitId, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isNotBlank(unitId)) {
            List<LeaderCount> countList = this.baseMapper.selectLeaderCount(Arrays.asList(unitId.split(",")));
            if (countList.size() > 0) {
                LeaderExcel(request, response, countList);
            }
        }
    }

    private void workExcel(HttpServletRequest request, HttpServletResponse response, List<StaffingLevelCount> countList) {
        String fileOutName = "单位编制与人员配备表" + DateUtil.dateToString(new Date(), "yyyyMMddHHmmss") + ".xlsx";
        try {
            FileInputStream fis = new FileInputStream(request.getServletContext().getRealPath("/excel") + "\\单位编制与人员配备表.xlsx");
            XSSFWorkbook wk = new XSSFWorkbook(fis);
            OutputStream out = response.getOutputStream();
            response.setContentType("application/x-download");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "filename=" + new String(fileOutName.getBytes("gbk"), "iso8859-1"));
            XSSFSheet sheet = wk.getSheetAt(0);
            int lastRow = sheet.getLastRowNum();
            short height = sheet.getRow(lastRow).getHeight();
            XSSFCellStyle style = sheet.getRow(lastRow).getCell(0).getCellStyle();
            style.setVerticalAlignment(VerticalAlignment.forInt( 1));
            XSSFFont font = wk.createFont();
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 12);
            style.setFont(font);
            int index = lastRow + 1;
            for (int i = 0; i < countList.size(); i++) {
                XSSFRow row = sheet.createRow(index);
                row.setHeight(height);
                XSSFCell cell = row.createCell(0);
                cell.setCellStyle(style);
                cell.setCellValue(countList.get(i).getB0101() == null ? "" : countList.get(i).getB0101());
                XSSFCell cell2 = row.createCell(1);
                cell2.setCellStyle(style);
                cell2.setCellValue(countList.get(i).getB0120() == null ? "" : countList.get(i).getB0120());
                XSSFCell cell3 = row.createCell(2);
                cell3.setCellStyle(style);
                cell3.setCellValue(countList.get(i).getB0122() == null ? "" : countList.get(i).getB0122());
                XSSFCell cell4 = row.createCell(3);
                cell4.setCellStyle(style);
                cell4.setCellValue(countList.get(i).getB0147() == null ? "" : countList.get(i).getB0147().toString());
                XSSFCell cell5 = row.createCell(4);
                cell5.setCellStyle(style);
                cell5.setCellValue(countList.get(i).getB0147b() == null ? "" : countList.get(i).getB0147b().toString());
                XSSFCell cell6 = row.createCell(5);
                cell6.setCellStyle(style);
                cell6.setCellValue(countList.get(i).getB0147m() == null ? "" : countList.get(i).getB0147m().toString());
                XSSFCell cell7 = row.createCell(6);
                cell7.setCellStyle(style);
                cell7.setCellValue(countList.get(i).getB0147s() == null ? "" : countList.get(i).getB0147s().toString());
                XSSFCell cell8 = row.createCell(7);
                cell8.setCellStyle(style);
                cell8.setCellValue(countList.get(i).getB0148() == null ? "" : countList.get(i).getB0148().toString());
                XSSFCell cell9 = row.createCell(8);
                cell9.setCellStyle(style);
                cell9.setCellValue(countList.get(i).getB0148b() == null ? "" : countList.get(i).getB0148b().toString());
                XSSFCell cell10 = row.createCell(9);
                cell10.setCellStyle(style);
                cell10.setCellValue(countList.get(i).getB0148m() == null ? "" : countList.get(i).getB0148m().toString());
                XSSFCell cell11 = row.createCell(10);
                cell11.setCellStyle(style);
                cell11.setCellValue(countList.get(i).getB0148s() == null ? "" : countList.get(i).getB0148s().toString());
                XSSFCell cell12 = row.createCell(11);
                cell12.setCellStyle(style);
                cell12.setCellValue(countList.get(i).getB0149() == null ? "" : countList.get(i).getB0149().toString());
                XSSFCell cell13 = row.createCell(12);
                cell13.setCellStyle(style);
                cell13.setCellValue(countList.get(i).getB0149b() == null ? "" : countList.get(i).getB0149b().toString());
                XSSFCell cell14 = row.createCell(13);
                cell14.setCellStyle(style);
                cell14.setCellValue(countList.get(i).getB0149m() == null ? "" : countList.get(i).getB0149m().toString());
                XSSFCell cell15 = row.createCell(14);
                cell15.setCellStyle(style);
                cell15.setCellValue(countList.get(i).getB0149s() == null ? "" : countList.get(i).getB0149s().toString());
                XSSFCell cell16 = row.createCell(15);
                cell16.setCellStyle(style);
                cell16.setCellValue(countList.get(i).getB0150() == null ? "" : countList.get(i).getB0150().toString());
                XSSFCell cell17 = row.createCell(16);
                cell17.setCellStyle(style);
                cell17.setCellValue(countList.get(i).getB0150b() == null ? "" : countList.get(i).getB0150b().toString());
                XSSFCell cell18 = row.createCell(17);
                cell18.setCellStyle(style);
                cell18.setCellValue(countList.get(i).getB0150m() == null ? "" : countList.get(i).getB0150m().toString());
                XSSFCell cell19 = row.createCell(18);
                cell19.setCellStyle(style);
                cell19.setCellValue(countList.get(i).getB0150s() == null ? "" : countList.get(i).getB0150s().toString());
                index++;
            }
            wk.write(out);
            fis.close();
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void LeaderExcel(HttpServletRequest request, HttpServletResponse response, List<LeaderCount> countList) {
        String fileOutName = "单位领导职数配备情况表" + DateUtil.dateToString(new Date(), "yyyyMMddHHmmss") + ".xlsx";
        try {
            FileInputStream fis = new FileInputStream(request.getServletContext().getRealPath("/excel") + "\\单位领导职数配备情况表.xlsx");
            XSSFWorkbook wk = new XSSFWorkbook(fis);
            OutputStream out = response.getOutputStream();
            response.setContentType("application/x-download");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "filename=" + new String(fileOutName.getBytes("gbk"), "iso8859-1"));
            XSSFSheet sheet = wk.getSheetAt(0);
            int lastRow = sheet.getLastRowNum();
            short height = sheet.getRow(lastRow).getHeight();
            XSSFCellStyle style = sheet.getRow(lastRow).getCell(0).getCellStyle();
            style.setVerticalAlignment(VerticalAlignment.forInt( 1));
            XSSFFont font = wk.createFont();
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 12);
            style.setFont(font);
            int index = lastRow + 1;
            for (int i = 0; i < countList.size(); i++) {
                XSSFRow row = sheet.createRow(index);
                row.setHeight(height);
                XSSFCell cell = row.createCell(0);
                cell.setCellStyle(style);
                cell.setCellValue(countList.get(i).getB0101() == null ? "" : countList.get(i).getB0101());
                XSSFCell cell2 = row.createCell(1);
                cell2.setCellStyle(style);
                cell2.setCellValue(countList.get(i).getB0120() == null ? "" : countList.get(i).getB0120());
                XSSFCell cell3 = row.createCell(2);
                cell3.setCellStyle(style);
                cell3.setCellValue(countList.get(i).getB0122() == null ? "" : countList.get(i).getB0122());
                XSSFCell cell4 = row.createCell(3);
                cell4.setCellStyle(style);
                cell4.setCellValue(countList.get(i).getB0145() == null ? "" : countList.get(i).getB0145().toString());
                XSSFCell cell5 = row.createCell(4);
                cell5.setCellStyle(style);
                cell5.setCellValue(countList.get(i).getB0145b() == null ? "" : countList.get(i).getB0145b().toString());
                XSSFCell cell6 = row.createCell(5);
                cell6.setCellStyle(style);
                cell6.setCellValue(countList.get(i).getB0145m() == null ? "" : countList.get(i).getB0145m().toString());
                XSSFCell cell7 = row.createCell(6);
                cell7.setCellStyle(style);
                cell7.setCellValue(countList.get(i).getB0145s() == null ? "" : countList.get(i).getB0145s().toString());
                XSSFCell cell8 = row.createCell(7);
                cell8.setCellStyle(style);
                cell8.setCellValue(countList.get(i).getB0146() == null ? "" : countList.get(i).getB0146().toString());
                XSSFCell cell9 = row.createCell(8);
                cell9.setCellStyle(style);
                cell9.setCellValue(countList.get(i).getB0146b() == null ? "" : countList.get(i).getB0146b().toString());
                XSSFCell cell10 = row.createCell(9);
                cell10.setCellStyle(style);
                cell10.setCellValue(countList.get(i).getB0146m() == null ? "" : countList.get(i).getB0146m().toString());
                XSSFCell cell11 = row.createCell(10);
                cell11.setCellStyle(style);
                cell11.setCellValue(countList.get(i).getB0146s() == null ? "" : countList.get(i).getB0146s().toString());
                XSSFCell cell12 = row.createCell(11);
                cell12.setCellStyle(style);
                cell12.setCellValue(countList.get(i).getB0145a() == null ? "" : countList.get(i).getB0145a().toString());
                XSSFCell cell13 = row.createCell(12);
                cell13.setCellStyle(style);
                cell13.setCellValue(countList.get(i).getB0146a() == null ? "" : countList.get(i).getB0146a().toString());
                index++;
            }
            wk.write(out);
            fis.close();
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<Chart> getMajorProport(String unitId) {
        return this.chartm.getMajorProport2(unitId);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<TeamMember> getteamMembers(String unitId) {
        return this.baseMapper.getteamMembers(unitId);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<Chart> getsourceProport(String unitId) {
        return this.chartm.getsourceProport(unitId);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public String orderUnit(Map<String, Object> map) {
        String newPdaCode21n;
        String newPdaCode21;
        String newPdaCode212;
        String newPdaCode;
        String fromId = map.get("fromId") != null ? map.get("fromId").toString() : "";
        String targetPid = map.get("targetPid") != null ? map.get("targetPid").toString() : "0";
        String targetId = map.get("targetId") != null ? map.get("targetId").toString() : "";
        String moveType = map.get("moveType") != null ? map.get("moveType").toString() : "";
        if (fromId == "" || targetId == "" || moveType == "") {
            this.b01m.updateAllEmptyParentid();
            return "操作失败";
        }
        B01 b = (B01) this.baseMapper.selectById(fromId);
        Map<String, Object> cxmap = new HashMap<>();
        cxmap.put("parentid", targetPid);
        cxmap.put("serialOrder", "1");
        cxmap.put("notflowid", fromId);
        List<B01> bList = selectByMaps(cxmap);
        List<B01> newList = new ArrayList<>();
        B01 bForm = (B01) this.baseMapper.selectById(fromId);
        String unitCode = bForm.getUnitcode();
        if (moveType.equals("inner")) {
            b.setParentid(targetId);
            newList.add(b);
            newList.addAll(bList);
        } else {
            b.setParentid(targetPid);
            if (bList.size() > 0) {
                for (int i = 0; i < bList.size(); i++) {
                    if (!targetId.equals(bList.get(i).getFlowid().toString())) {
                        newList.add(bList.get(i));
                    } else if (moveType.equals("prev")) {
                        newList.add(b);
                        newList.add(bList.get(i));
                    } else if (moveType.equals("next")) {
                        newList.add(bList.get(i));
                        newList.add(b);
                    }
                }
            } else {
                newList.add(b);
            }
        }
        for (int n = 0; n < newList.size(); n++) {
            B01 b2 = newList.get(n);
            b2.setSerial(Short.valueOf((short) (n + 1)));
            updateById(b2);
        }
        Map<String, Object> cxmap2 = new HashMap<>();
        cxmap2.put("sflowid", fromId);
        cxmap2.put("UNITCODEOrder", "1");
        cxmap2.put("notflowid", fromId);
        List<B01> fromChildList = selectByMapsTree(cxmap2);
        if (moveType.equals("inner")) {
//            String targetUnitCode = ((B01) this.baseMapper.selectById(targetId)).getUnitcode();
//            String targetMaxCode = this.b01m.selectMaxUnitcode(targetUnitCode, targetUnitCode.length() + 2);
//            if (targetMaxCode == null || targetMaxCode.trim().isEmpty()) {
//                newPdaCode = targetUnitCode + "01";
//            } else {
//                int serial = Integer.parseInt(targetMaxCode.replaceFirst(targetUnitCode, ""));
//                if (serial < 9) {
//                    newPdaCode = targetUnitCode + "0" + String.valueOf(serial + 1);
//                } else {
//                    newPdaCode = targetUnitCode + String.valueOf(serial + 1);
//                }
//            }
            for (int n2 = 0; n2 < fromChildList.size(); n2++) {
                B01 b22 = fromChildList.get(n2);
//                String newChildPdaCode = newPdaCode + b22.getUnitcode().substring(unitCode.length());
//                b22.setUnitcode(newChildPdaCode);
//                b22.setPdacode(b22.getPdacode() == null ? null : newChildPdaCode);
                updateById(b22);
            }
            bForm.setSerial(null);
            bForm.setParentid(targetId);
//            bForm.setUnitcode(newPdaCode);
//            bForm.setPdacode(bForm.getPdacode() == null ? null : newPdaCode);
            updateById(bForm);
        } else if (moveType.equals("prev")) {
//            String targetPDACode = ((B01) this.baseMapper.selectById(targetId)).getUnitcode();
//            String pPDACode = targetPDACode.substring(0, targetPDACode.length() - 2);
//            String sPDACode = targetPDACode.substring(targetPDACode.length() - 2);
//            Map<String, Object> cxmap1 = new HashMap<>();
//            cxmap1.put("UNITCODERight", pPDACode);
//            cxmap1.put("UNITCODEOrder", "1");
//            cxmap1.put("UNITCODELen", Integer.valueOf(pPDACode.length() + 2));
//            cxmap1.put("notUNITCODE", pPDACode);
//            List<B01> targetChildList = selectByMaps(cxmap1);
//            for (int n1 = targetChildList.size() - 1; n1 >= 0; n1--) {
//                B01 b21 = targetChildList.get(n1);
//                String b21pdacode = targetChildList.get(n1).getUnitcode();
//                if (!b21pdacode.equals(bForm.getUnitcode())) {
//                    String b21sPDACode = b21pdacode.substring(b21pdacode.length() - 2);
//                    int serial21 = 0;
//                    try {
//                        serial21 = Integer.parseInt(b21sPDACode);
//                    } catch (Exception e) {
//                    }
//                    if (serial21 < 9) {
//                        newPdaCode212 = pPDACode + "0" + String.valueOf(serial21 + 1);
//                    } else {
//                        newPdaCode212 = pPDACode + String.valueOf(serial21 + 1);
//                    }
//                    if (Integer.parseInt(b21sPDACode) >= Integer.parseInt(sPDACode)) {
//                        new HashMap();
//                        Map<String, Object> cxmap3 = new HashMap<>();
//                        cxmap3.put("sflowid", targetChildList.get(n1).getFlowid());
//                        cxmap3.put("UNITCODEOrder", "1");
//                        cxmap3.put("notflowid", targetChildList.get(n1).getFlowid());
//                        List<B01> b21ChildList = selectByMapsTree(cxmap3);
//                        for (int n11 = 0; n11 < b21ChildList.size(); n11++) {
//                            B01 b211 = b21ChildList.get(n11);
//                            String newChildPdaCode21 = newPdaCode212 + b211.getUnitcode().substring(b21pdacode.length());
//                            b211.setUnitcode(newChildPdaCode21);
//                            b211.setPdacode(b211.getPdacode() == null ? null : newChildPdaCode21);
//                            updateById(b211);
//                        }
//                        b21.setUnitcode(newPdaCode212);
//                        b21.setPdacode(b21.getPdacode() == null ? null : newPdaCode212);
//                        updateById(b21);
//                    }
//                }
//            }
//            Map<String, Object> cxmap4 = new HashMap<>();
//            cxmap4.put("sflowid", bForm.getFlowid());
//            cxmap4.put("UNITCODEOrder", "1");
//            cxmap4.put("notflowid", bForm.getFlowid());
//            List<B01> b21nChildList = selectByMapsTree(cxmap4);
//            for (int n11n = 0; n11n < b21nChildList.size(); n11n++) {
//                B01 b211n = b21nChildList.get(n11n);
//                String newChildPdaCode21n = targetPDACode + b211n.getUnitcode().substring(unitCode.length());
//                b211n.setUnitcode(newChildPdaCode21n);
//                b211n.setPdacode(b211n.getPdacode() == null ? null : newChildPdaCode21n);
//                updateById(b211n);
//            }
            bForm.setSerial(null);
            bForm.setParentid(targetPid);
//            bForm.setUnitcode(targetPDACode);
//            bForm.setPdacode(bForm.getPdacode() == null ? null : targetPDACode);
            updateById(bForm);
        } else {
            String targetPDACode2 = ((B01) this.baseMapper.selectById(targetId)).getUnitcode();
//            Map<String, Object> cxmap12 = new HashMap<>();
//            String pPDACode2 = (null==targetPDACode2||targetPDACode2=="")?"":targetPDACode2.substring(0, targetPDACode2.length() - 2);
//            String sPDACode2 = (null==targetPDACode2||targetPDACode2=="")?"":targetPDACode2.substring(targetPDACode2.length() - 2);
//            cxmap12.put("UNITCODERight", pPDACode2);
//            cxmap12.put("UNITCODEOrder", "1");
//            cxmap12.put("UNITCODELen", Integer.valueOf(pPDACode2.length() + 2));
//            cxmap12.put("notUNITCODE", pPDACode2);
//            List<B01> targetChildList2 = selectByMaps(cxmap12);
//            for (int n12 = targetChildList2.size() - 1; n12 >= 0; n12--) {
//                B01 b212 = targetChildList2.get(n12);
//                String b21pdacode2 = targetChildList2.get(n12).getUnitcode();
//                if (!b21pdacode2.equals(bForm.getUnitcode())) {
//                    String b21sPDACode2 = b21pdacode2.substring(b21pdacode2.length() - 2);
//                    int serial212 = 0;
//                    try {
//                        serial212 = Integer.parseInt(b21sPDACode2);
//                    } catch (Exception e2) {
//                    }
//                    if (serial212 < 9) {
//                        newPdaCode21 = pPDACode2 + "0" + String.valueOf(serial212 + 1);
//                    } else {
//                        newPdaCode21 = pPDACode2 + String.valueOf(serial212 + 1);
//                    }
//                    if (Integer.parseInt(b21sPDACode2) > Integer.parseInt(sPDACode2)) {
//                        Map<String, Object> cxmap5 = new HashMap<>();
//                        cxmap5.put("sflowid", targetChildList2.get(n12).getFlowid());
//                        cxmap5.put("UNITCODEOrder", "1");
//                        cxmap5.put("notflowid", targetChildList2.get(n12).getFlowid());
//                        List<B01> b21ChildList2 = selectByMapsTree(cxmap5);
//                        for (int n112 = 0; n112 < b21ChildList2.size(); n112++) {
//                            B01 b2112 = b21ChildList2.get(n112);
//                            String newChildPdaCode212 = newPdaCode21 + b2112.getUnitcode().substring(b21pdacode2.length());
//                            b2112.setUnitcode(newChildPdaCode212);
//                            b2112.setPdacode(b2112.getPdacode() == null ? null : newChildPdaCode212);
//                            updateById(b2112);
//                        }
//                        b212.setUnitcode(newPdaCode21);
//                        b212.setPdacode(b212.getPdacode() == null ? null : newPdaCode21);
//                        updateById(b212);
//                    }
//                }
//            }
//            int serial21n = 0;
//            try {
//                serial21n = Integer.parseInt(sPDACode2);
//            } catch (Exception e3) {
//            }
//            if (serial21n < 9) {
//                newPdaCode21n = pPDACode2 + "0" + String.valueOf(serial21n + 1);
//            } else {
//                newPdaCode21n = pPDACode2 + String.valueOf(serial21n + 1);
//            }
            Map<String, Object> cxmap6 = new HashMap<>();
            cxmap6.put("sflowid", bForm.getFlowid());
            cxmap6.put("UNITCODEOrder", "1");
            cxmap6.put("notflowid", bForm.getFlowid());
            List<B01> b21nChildList2 = selectByMapsTree(cxmap6);
//            for (int n11n2 = 0; n11n2 < b21nChildList2.size(); n11n2++) {
//                B01 b211n2 = b21nChildList2.get(n11n2);
//                String newChildPdaCode21n2 = newPdaCode21n + b211n2.getUnitcode().substring(unitCode.length());
//                b211n2.setUnitcode(newChildPdaCode21n2);
//                b211n2.setPdacode(b211n2.getPdacode() == null ? null : newChildPdaCode21n2);
//                updateById(b211n2);
//            }
            bForm.setSerial(null);
            bForm.setParentid(targetPid);
//            bForm.setUnitcode(newPdaCode21n);
//            bForm.setPdacode(bForm.getPdacode() == null ? null : newPdaCode21n);
            updateById(bForm);
        }
        this.b01m.updateAllEmptyParentid();
        return "操作成功";
    }

    private List<B01> selectByMapsTree(Map<String, Object> map) {
        try {
            return this.b01m.selectByMapsTree(map);
        }catch (Exception e){
            return new ArrayList<>();
        }
    }

    private B01 setUnitSerial(B01 b) {
        short serial = 99;
        try {
            serial = Short.parseShort(b.getUnitcode().substring(b.getUnitcode().length() - 2));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        b.setSerial(Short.valueOf(serial));
        return b;
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public String orderUnitPdacode(Map<String, Object> map) {
        String newPdaCode21n;
        String newPdaCode21;
        String newPdaCode212;
        String newPdaCode;
        String fromId = map.get("fromId") != null ? map.get("fromId").toString() : "";
        String targetId = map.get("targetId") != null ? map.get("targetId").toString() : "";
        String moveType = map.get("moveType") != null ? map.get("moveType").toString() : "";
        if (fromId == "" || targetId == "" || moveType == "") {
            return "操作失败";
        }
        B01 bForm = (B01) this.baseMapper.selectById(fromId);
        String fromPDACode = bForm.getPdacode();
        LambdaQueryWrapper<B01> lambdaQueryWrapper = new LambdaQueryWrapper();
        QueryWrapper<B01> wrapper = new QueryWrapper<>();
        //（已调整完毕） todo:将下面的sql查询迁移到xml文件中
        List<B01> fromChildList = selectList(lambdaQueryWrapper.like
        (B01::getPdacode, "%"+fromPDACode).notIn(B01::getFlowid, fromId).orderByAsc(B01::getPdacode));
        if (moveType.equals("inner")) {
            String targetPDACode = ((B01) this.baseMapper.selectById(targetId)).getPdacode();
            String targetMaxCode = this.b01m.selectMaxPdacode(targetPDACode, targetPDACode.length() + 2);
            if (targetMaxCode == null || targetMaxCode.trim().isEmpty()) {
                newPdaCode = targetPDACode + "01";
            } else {
                int serial = Integer.parseInt(targetMaxCode.replaceFirst(targetPDACode, ""));
                if (serial < 9) {
                    newPdaCode = targetPDACode + "0" + String.valueOf(serial + 1);
                } else {
                    newPdaCode = targetPDACode + String.valueOf(serial + 1);
                }
            }
            for (int n = 0; n < fromChildList.size(); n++) {
                B01 b2 = fromChildList.get(n);
                b2.setPdacode(newPdaCode + b2.getPdacode().substring(fromPDACode.length()));
                updateById(b2);
            }
            bForm.setPdacode(newPdaCode);
            updateById(bForm);
            return "操作成功";
        } else if (moveType.equals("prev")) {
            String targetPDACode2 = ((B01) this.baseMapper.selectById(targetId)).getPdacode();
            String pPDACode = targetPDACode2.substring(0, targetPDACode2.length() - 2);
            String sPDACode = targetPDACode2.substring(targetPDACode2.length() - 2);
            LambdaQueryWrapper<B01> lambdaQueryWrapper1 = new LambdaQueryWrapper();
            //（已调整完毕） todo:将下面的sql查询迁移到xml文件中
            List<B01> targetChildList = selectList(lambdaQueryWrapper1.like(B01::getPdacode,"%"+ pPDACode).
                    apply("LENGTH(PDACODE) = {0}", Integer.valueOf(pPDACode.length() + 2)).notIn(B01::getPdacode, pPDACode).orderByAsc(B01::getPdacode));
            for (int n1 = targetChildList.size() - 1; n1 >= 0; n1--) {
                B01 b21 = targetChildList.get(n1);
                String b21pdacode = targetChildList.get(n1).getPdacode();
                String b21sPDACode = b21pdacode.substring(b21pdacode.length() - 2);
                int serial21 = 0;
                try {
                    serial21 = Integer.parseInt(b21sPDACode);
                } catch (Exception e) {
                }
                if (serial21 < 9) {
                    newPdaCode212 = pPDACode + "0" + String.valueOf(serial21 + 1);
                } else {
                    newPdaCode212 = pPDACode + String.valueOf(serial21 + 1);
                }
                if (Integer.parseInt(b21sPDACode) >= Integer.parseInt(sPDACode)) {
                    LambdaQueryWrapper<B01> lambdaQueryWrapper2 = new LambdaQueryWrapper();
                    //（已调整完毕） todo:将下面的sql查询迁移到xml文件中
                    List<B01> b21ChildList = selectList(lambdaQueryWrapper2.like(B01::getPdacode, "%"+b21pdacode).
                            notIn(B01::getPdacode, b21pdacode).orderByAsc(B01::getPdacode));
                    for (int n11 = 0; n11 < b21ChildList.size(); n11++) {
                        B01 b211 = b21ChildList.get(n11);
                        b211.setPdacode(newPdaCode212 + b211.getPdacode().substring(b21pdacode.length()));
                        updateById(b211);
                    }
                    b21.setPdacode(newPdaCode212);
                    updateById(b21);
                }
            }
            LambdaQueryWrapper<B01> lambdaQueryWrapper3 = new LambdaQueryWrapper();
            //（已调整完毕） todo:将下面的sql查询迁移到xml文件中
            List<B01> b21nChildList = selectList(lambdaQueryWrapper3.like(B01::getPdacode, "%"+fromPDACode).
                    notIn(B01::getPdacode, fromPDACode).orderByAsc(B01::getPdacode));
            for (int n11n = 0; n11n < b21nChildList.size(); n11n++) {
                B01 b211n = b21nChildList.get(n11n);
                b211n.setPdacode(targetPDACode2 + b211n.getPdacode().substring(fromPDACode.length()));
                updateById(b211n);
            }
            bForm.setPdacode(targetPDACode2);
            updateById(bForm);
            return "操作成功";
        } else {
            String targetPDACode3 = ((B01) this.baseMapper.selectById(targetId)).getPdacode();
            String pPDACode2 = targetPDACode3.substring(0, targetPDACode3.length() - 2);
            String sPDACode2 = targetPDACode3.substring(targetPDACode3.length() - 2);
            LambdaQueryWrapper<B01> lambdaQueryWrapper4 = new LambdaQueryWrapper();
            //（已调整完毕） todo:将下面的sql查询迁移到xml文件中
            List<B01> targetChildList2 = selectList(lambdaQueryWrapper4.like(B01::getPdacode, "%"+pPDACode2).
                    apply("length(PDACODE) = {0}", Integer.valueOf(pPDACode2.length() + 2)).
                    notIn(B01::getPdacode, pPDACode2).orderByAsc(B01::getPdacode));

            for (int n12 = targetChildList2.size() - 1; n12 >= 0; n12--) {
                B01 b212 = targetChildList2.get(n12);
                String b21pdacode2 = targetChildList2.get(n12).getPdacode();
                String b21sPDACode2 = b21pdacode2.substring(b21pdacode2.length() - 2);
                int serial212 = 0;
                try {
                    serial212 = Integer.parseInt(b21sPDACode2);
                } catch (Exception e2) {
                }
                if (serial212 < 9) {
                    newPdaCode21 = pPDACode2 + "0" + String.valueOf(serial212 + 1);
                } else {
                    newPdaCode21 = pPDACode2 + String.valueOf(serial212 + 1);
                }
                if (Integer.parseInt(b21sPDACode2) > Integer.parseInt(sPDACode2)) {
                    LambdaQueryWrapper<B01> lambdaQueryWrapper5 = new LambdaQueryWrapper();
                    //（已调整完毕） todo:将下面的sql查询迁移到xml文件中
                    List<B01> b21ChildList2 = selectList(lambdaQueryWrapper5.like(B01::getPdacode, "%"+b21pdacode2).
                            notIn(B01::getPdacode, b21pdacode2).orderByAsc(B01::getPdacode));
                    for (int n112 = 0; n112 < b21ChildList2.size(); n112++) {
                        B01 b2112 = b21ChildList2.get(n112);
                        b2112.setPdacode(newPdaCode21 + b2112.getPdacode().substring(b21pdacode2.length()));
                        updateById(b2112);
                    }
                    b212.setPdacode(newPdaCode21);
                    updateById(b212);
                }
            }
            int serial21n = 0;
            try {
                serial21n = Integer.parseInt(sPDACode2);
            } catch (Exception e3) {
            }
            if (serial21n < 9) {
                newPdaCode21n = pPDACode2 + "0" + String.valueOf(serial21n + 1);
            } else {
                newPdaCode21n = pPDACode2 + String.valueOf(serial21n + 1);
            }
            LambdaQueryWrapper<B01> lambdaQueryWrapper6 = new LambdaQueryWrapper();
            //（已调整完毕） todo:将下面的sql查询迁移到xml文件中
            List<B01> b21nChildList2 = selectList(lambdaQueryWrapper6.like(B01::getPdacode, "%"+fromPDACode).
                    notIn(B01::getPdacode, fromPDACode).orderByAsc(B01::getPdacode));
            for (int n11n2 = 0; n11n2 < b21nChildList2.size(); n11n2++) {
                B01 b211n2 = b21nChildList2.get(n11n2);
                b211n2.setPdacode(newPdaCode21n + b211n2.getPdacode().substring(fromPDACode.length()));
                updateById(b211n2);
            }
            bForm.setPdacode(newPdaCode21n);
            updateById(bForm);
            return "操作成功";
        }
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public int initB01Actual() {
        return this.b01m.initB01Actual();
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public int syncPDAOrder() {
        initB01UnitCode();
        return 1;
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<Chart> getSurpassUnitCount(String userId, String unitCode) {
        return this.b01m.getSurpassUnitCount(userId, unitCode);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<Chart> getMissUnitCount(String userId, String unitCode) {
        return this.b01m.getMissUnitCount(userId, unitCode);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public String getMaxCode(String parentid) {
        return this.b01m.getMaxCode(parentid);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public PageUtils getSurpassUnit(Map<String, Object> map) {
        map.put("page", (String) map.get("pageNum"));
        map.put("limit", (String) map.get("pageSize"));
        Page<B01> page = new Query(map).getPage();
        return new PageUtils(page.setRecords(this.b01m.getSurpassUnit(page, map)));
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public PageUtils getMissUnit(Map<String, Object> map) {
        map.put("page", (String) map.get("pageNum"));
        map.put("limit", (String) map.get("pageSize"));
        Page<B01> page = new Query(map).getPage();
        return new PageUtils(page.setRecords(this.b01m.getMissUnit(page, map)));
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public void initB01ActualByUnitid(String unitid) {
        this.b01m.initB01ActualByUnitid(unitid);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public void updatePdaCode(B01 b) {
        this.b01m.updatePdaCode(b);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<B01> getSurpassUnitb(Map<String, Object> map) {
        return this.b01m.getSurpassUnit(map);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<B01> getMissUnitb(Map<String, Object> map) {
        return this.b01m.getMissUnit(map);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    @Transactional
    public void initB01UnitCode() {
        Map<String, Object> pMap = new HashMap<>();
        pMap.put("serialOrder", "1");
        this.allList = this.b01m.selectByMaps(pMap);
        pMap.put("parentid", "0");
        int i = 1;
        for (B01 rootDept : this.b01m.selectRoots(pMap)) {
            i++;
            String unitcode = String.format("%02d", Integer.valueOf(i));
            rootDept.setUnitcode(unitcode);
            rootDept.setPdacode(unitcode);
            this.updateList.add(rootDept);
            recursionInitUnitCode(rootDept);
        }
        if (this.updateList != null && this.updateList.size() > 0) {
            this.b01m.batchUpdate(this.updateList);
        }
    }

    private void recursionInitUnitCode(B01 parentEntity) {
        int i = 1;
        List<B01> childList = (List) this.allList.stream().filter(t -> {
            return t.getParentid().equals(parentEntity.getFlowid());
        }).sorted(Comparator.comparing((v0) -> {
            return v0.getSerial();
        }, Comparator.nullsLast((v0, v1) -> {
            return v0.compareTo(v1);
        }))).collect(Collectors.toList());
        if (!(childList == null || childList.size() == 0)) {
            for (B01 b01 : childList) {
                System.out.println("parentCode:" + parentEntity.getUnitcode());
                i++;
                String unitCode = parentEntity.getUnitcode() + String.format("%02d", Integer.valueOf(i));
                b01.setUnitcode(unitCode);
                b01.setPdacode(unitCode);
                this.updateList.add(b01);
                recursionInitUnitCode(b01);
            }
        }
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public boolean deleteBatchIdsChild(List<String> list) {
        return this.b01m.deleteBatchIdsChild(list);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<B01> selectByMaps(Map<String, Object> map) {
        return this.b01m.selectByMaps(map);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public String getMaxCodeLenTwo() {
        return this.b01m.getMaxCodeLenTwo();
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public int updateNavigatDeptUnitcode() {
        return this.b01m.updateNavigatDeptUnitcode();
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public int updatePdaCodeByMap(Map<String, Object> pMap) {
        return this.b01m.updatePdaCodeByMap(pMap);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<Chart> getFull63InAppointUnit() {
        return this.b01m.getFull63InAppointUnit();
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<Chart> getPunish() {
        return this.b01m.getPunish();
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<Chart> getNewDutiesYear(String current_year_string) {
        return this.b01m.getNewDutiesYear(current_year_string);
    }

    @Override // com.tdqy.cadre.modular.profess.service.UnitInfoService
    public List<Chart> getProbation() {
        return this.b01m.getProbation();
    }
    @Override
    @Transactional
    public R saveVueUnit(Map<String,Object> param) {
        String flowid = GenerateUUID.getUUID();
        //新增单位基本信息
        B01 b = new B01() ;
        Map<String, Object> b01Map = (Map<String, Object>) param.get("unitForm");
        b.setB0101((String)b01Map.get("b0101"));
        b.setParentid((String)b01Map.get("parentId"));
        b.setB0120(b01Map.get("b0120") == null ? null : (String)b01Map.get("b0120"));
        b.setB0122(b01Map.get("b0122") == null ? null : (String)b01Map.get("b0122"));
        b.setB0115(b01Map.get("b0115") == null ? null : (String)b01Map.get("b0115"));
        b.setB0116(b01Map.get("b0116") == null ? null : (String)b01Map.get("b0116"));
        b.setB0117(b01Map.get("b0117") == null ? null : (String)b01Map.get("b0117"));
        Map<String, Object> map = new HashMap<>();
        map.put("b0101", b.getB0101());
        map.put("parentid", b.getParentid());
        if (selectByMaps(map).size() > 0) {
            return R.ok("已存在该单位名称!");
        }

        b.setFlowid(flowid);
        if (b.getParentid() != null) {
            b.setUnitcode(getUnitCode(b.getParentid()));
        }
        if (b.getParentid() == null || b.getParentid().isEmpty()) {
            b.setParentid(GenerateUUID.getUUID());
        }
        short serial = 99;
        try {
            if (null != b.getUnitcode() && b.getUnitcode() != "") {
                serial = Short.parseShort(b.getUnitcode().substring(b.getUnitcode().length() - 2));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        b.setSerial(Short.valueOf(serial));
        List<Map<String, Object>> pList1 = (List) param.get("positionData");
        if(null != pList1 && pList1.size()>0){
            for(Map<String, Object> pmap : pList1){
                if(pmap.get("type")!=null){
                    if(pmap.get("type").equals("正职")){
                        if (pmap.get("b4103") != null) {
                            b.setB0145(Short.valueOf(Short.parseShort(pmap.get("b4103").toString())));
                            b.setB0145s(Short.valueOf(Short.parseShort(pmap.get("b4103").toString())));
                        }

                    }else if(pmap.get("type").equals("副职")){
                        b.setB0146(Short.valueOf(Short.parseShort(pmap.get("b4103").toString())));
                        b.setB0146s(Short.valueOf(Short.parseShort(pmap.get("b4103").toString())));
                    }else{
                        b.setB0154(Short.valueOf(Short.parseShort(pmap.get("b4103").toString())));
                        b.setB0154s(Short.valueOf(Short.parseShort(pmap.get("b4103").toString())));
                    }
                }
            }
        }


        addUnit(b);
        SysRoleDataEntity s = new SysRoleDataEntity();
        LoginUser user = SecurityUtils.getLoginUser();
        s.setFlowid(GenerateUUID.getUUID());

        s.setRoleid(SecurityUtils.getLoginUser().getUser().getRoleId());
        s.setUnitid(flowid);
        s.setRwflag("2");
        this.sysRoleDataService.insertSysRoleData(s);

        //新增班子信息
        List<Map<String, Object>> pList = (List) param.get("positionData");
        if(null != pList && pList.size()>0){
            for(Map<String, Object> pmap : pList){
                B04 b04 = new B04();
                b04.setUnitid(flowid);
                b04.setFlowid(GenerateUUID.getUUID());
                if (pmap.get("b4101") != null) {
                    b04.setB0401(pmap.get("type").toString());
                }
                if (pmap.get("b4102") != null) {
                    b04.setB0402(pmap.get("b4102").toString());
                }
                if (pmap.get("b4103") != null) {
                    b04.setB0403(Short.valueOf(Short.parseShort(pmap.get("b4103").toString())));
                }
                if (pmap.get("b4104") != null) {
                    b04.setB0404(pmap.get("b4104").toString());
                }
                if (pmap.get("b4105") != null) {
                    b04.setB0405(pmap.get("b4105").toString());
                }
                if (map.get("unitid") != null) {
                    b04.setUnitid(map.get("unitid").toString());
                }
                this.b04Service.getBaseMapper().insert(b04);
            }
        }

        //新增班子运行情况信息
        List<Map<String,Object>> b41List = (List) param.get("operationData");
        for(Map<String,Object> b41map : b41List){
            B41 b41 = new B41();
            if(null != b41map.get("b4101")){
                b41.setB4101(b41map.get("b4101").toString());
            }
            if(null != b41map.get("b4105")){
                b41.setB4105(b41map.get("b4105").toString());
            }
            if(null != b41map.get("b4110")){
                b41.setB4110(b41map.get("b4110").toString());
            }
            b41.setFlowid(GenerateUUID.getUUID());
            b41.setUnitid(flowid);
            b41Service.getBaseMapper().insert(b41);
        }
        return R.ok();
    }

    private String getUnitCode(String parentid) {
        String maxCode = getMaxCode(parentid);
        if (((B01) getById(parentid)) == null) {
            maxCode = getMaxCodeLenTwo();
        }
        if (maxCode == null || maxCode.length() < 2) {
            B01 b = (B01) getById(parentid);
            if (b == null || b.getUnitcode() == null) {
                return "01";
            }
            return b.getUnitcode() + "01";
        }
        int i = Integer.parseInt(maxCode.substring(maxCode.length() - 2, maxCode.length())) + 1;
        if (i < 10) {
            if (maxCode.length() == 2) {
                return "0" + i;
            }
            return maxCode.substring(0, maxCode.length() - 2) + "0" + i;
        } else if (maxCode.length() == 2) {
            return "" + i;
        } else {
            return maxCode.substring(0, maxCode.length() - 2) + i;
        }
    }

    public R updateVueUnit(@RequestBody Map<String,Object> param){
        Map<String, Object> b01Map = (Map<String, Object>) param.get("unitForm");
        List<Map<String, Object>> pList1 = (List) param.get("positionData");
        B01 b = createB01(b01Map,pList1);
        String flowid = b.getFlowid();
        if (b.getFlowid().equals(b.getParentid())) {
            return R.ok("不能选择修改单位本单位作为父级单位!");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("b0101", b.getB0101());
        map.put("parentid", b.getParentid());
        map.put("notflowid", b.getFlowid());
        List<B01> repeatList = selectByMaps(map);
        if (repeatList != null && repeatList.size() > 0) {
            for(B01 b01:repeatList){
                if(b01.getFlowid() !=flowid ){
                    return R.ok("保存失败，同一节点下不能存在相同名称!");
                }
            }
        }
        B01 b1 = (B01) getById(b.getFlowid());
        if (null != b && null != b1.getParentid() && b1.getParentid() != "") {
            B01 pEntity = (B01) getById(b1.getParentid());
            if (b.getParentid() == null || b.getParentid().isEmpty()) {
                if (pEntity == null) {
                }
            } else if (pEntity == null) {
                b.setUnitcode(getUnitCode(b.getParentid()));
            } else if (!b.getParentid().equals(b1.getParentid())) {
                b.setUnitcode(getUnitCode(b.getParentid()));
            }
        }
        if (b.getPdacode() == "") {
            updatePdaCode(b);
        } else if (b1.getPdacode() != null) {
            b.setPdacode(null);
        }
        if (b.getParentid() == null || b.getParentid().isEmpty()) {
            b.setParentid(GenerateUUID.getUUID());
        }
        short serial = 99;
        try {
            if(null!= b.getUnitcode() && b.getUnitcode() !=""){
                serial = Short.parseShort(b.getUnitcode().substring(b.getUnitcode().length() - 2));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        b.setSerial(Short.valueOf(serial));
        if (!saveOrUpdate(b)) {
            return R.ok("保存失败!");
        }
        try {
            updateNavigatDeptUnitcode();
        } catch (Exception ex2) {
            ex2.printStackTrace();
        }


        //修改班子信息
        List<Map<String, Object>> pList = (List) param.get("positionData");
        if(null != pList && pList.size()>0) {
            for (Map<String, Object> pmap : pList) {
                B04 b04 = (B04) this.b04Service.getBaseMapper().selectById(pmap.get("flowid").toString());
                if(null != b04){
                    if (pmap.get("b4101") != null) {
                        b04.setB0401(pmap.get("type").toString());
                    }
                    if (pmap.get("b4102") != null) {
                        b04.setB0402(pmap.get("b4102").toString());
                    }
                    if (pmap.get("b4103") != null) {
                        b04.setB0403(Short.valueOf(Short.parseShort(pmap.get("b4103").toString())));
                    }
                    if (pmap.get("b4104") != null) {
                        b04.setB0404(pmap.get("b4104").toString());
                    }
                    if (pmap.get("b4105") != null) {
                        b04.setB0405(pmap.get("b4105").toString());
                    }
                    if (flowid != null) {
                        b04.setUnitid(flowid);
                    }
                    ValidatorUtils.validateEntity(b04, new Class[0]);
                    this.b04Service.getBaseMapper().updateById(b04);
                }else{
                    b04 = new B04();
                    if (pmap.get("b4101") != null) {
                        b04.setB0401(pmap.get("type").toString());
                    }
                    if (pmap.get("b4102") != null) {
                        b04.setB0402(pmap.get("b4102").toString());
                    }
                    if (pmap.get("b4103") != null) {
                        b04.setB0403(Short.valueOf(Short.parseShort(pmap.get("b4103").toString())));
                    }
                    if (pmap.get("b4104") != null) {
                        b04.setB0404(pmap.get("b4104").toString());
                    }
                    if (pmap.get("b4105") != null) {
                        b04.setB0405(pmap.get("b4105").toString());
                    }
                    if (flowid != null) {
                        b04.setUnitid(flowid);
                    }
                    ValidatorUtils.validateEntity(b04, new Class[0]);
                    this.b04Service.getBaseMapper().insert(b04);
                }
            }
        }


        //修改班子运行情况信息
        List<Map<String,Object>> b41List = (List) param.get("operationData");
        for(Map<String,Object> b41map : b41List){
            B41 b41 = new B41();
            if(null != b41map.get("b4101")){
                b41.setB4101(b41map.get("b4101").toString());
            }
            if(null != b41map.get("b4105")){
                b41.setB4105(b41map.get("b4105").toString());
            }
            if(null != b41map.get("b4110")){
                b41.setB4110(b41map.get("b4110").toString());
            }
            b41.setUnitid(b41map.get("unitid").toString());
            b41.setFlowid(b41map.get("flowid").toString());
            ValidatorUtils.validateEntity(b41, new Class[0]);
            this.b41Service.getBaseMapper().updateById(b41);
        }


        return R.ok();
    }

    private B01 createB01(Map<String, Object> b01Map,List<Map<String, Object>> pList1) {
        B01 b = new B01() ;
        b.setB0101((String)b01Map.get("b0101"));
        b.setParentid((String)b01Map.get("parentId"));
        b.setB0103(b01Map.get("b0103") == null ? null : (String)b01Map.get("b0103"));
        b.setB0115(b01Map.get("b0115") == null ? null : (String)b01Map.get("b0115"));
        b.setB0116(b01Map.get("b0116") == null ? null : (String)b01Map.get("b0116"));
        b.setB0117(b01Map.get("b0117") == null ? null : (String)b01Map.get("b0117"));
        b.setB0120(b01Map.get("b0120") == null ? null : (String)b01Map.get("b0120"));
        b.setB0122(b01Map.get("b0122") == null ? null : (String)b01Map.get("b0122"));
        b.setPdacode(b01Map.get("pdacode") == null ? null : (String)b01Map.get("pdacode"));
        b.setFlowid(b01Map.get("flowid").toString());
        b.setSerial(b01Map.get("serial") == null ? null : Short.parseShort(b01Map.get("serial").toString()));
        if(null != pList1 && pList1.size()>0){
            for(Map<String, Object> pmap : pList1){
                if(pmap.get("type")!=null){
                    if(pmap.get("type").equals("正职")){
                        if (pmap.get("b4103") != null) {
                            b.setB0145(Short.valueOf(Short.parseShort(pmap.get("b4103").toString())));
                            b.setB0145s(Short.valueOf(Short.parseShort(pmap.get("b4103").toString())));
                        }

                    }else if(pmap.get("type").equals("副职")){
                        b.setB0146(Short.valueOf(Short.parseShort(pmap.get("b4103").toString())));
                        b.setB0146s(Short.valueOf(Short.parseShort(pmap.get("b4103").toString())));
                    }else{
                        b.setB0154(Short.valueOf(Short.parseShort(pmap.get("b4103").toString())));
                        b.setB0154s(Short.valueOf(Short.parseShort(pmap.get("b4103").toString())));
                    }
                }
            }
        }
        return b;
    }

}
